import { getTemplateConfig } from '@/config/template';
import moment from 'moment';
import Taro from '@tarojs/taro';
import { IStatisticsEvent, IStatisticsExtra } from './GStatisticsEvent';
import * as GStatisticsEvent from './GStatisticsEvent';


export { GStatisticsEvent };

const config = getTemplateConfig();

class GStatistics {

  static checkExtra(extra: IStatisticsExtra) {
    for (const key in extra) {
      if (extra.hasOwnProperty(key)) {
        const element = extra[key];
        if (typeof element === 'boolean') {
          // 布尔值自动转化为整数
          extra[key] = GStatistics.boolenIntValue(element);
        }
      }
    }
  }

  static async postCalculateEvent({ id, extra }: IStatisticsEvent<IStatisticsExtra>) {
    // eslint-disable-next-line no-undef
    const post = config.supportStatistical && process.env.NODE_ENV !== 'development';
    if (post) {
      console.log('postCalculateEvent', id, extra);
      extra && GStatistics.checkExtra(extra);
      Taro.reportEvent(id, extra || {});
    }
  }

  static timeDiff(start: moment.Moment, end: moment.Moment) {
    const diff = end.valueOf() - start.valueOf();
    return diff;
  }

  static timeDiffToNow(start: moment.Moment) {
    return GStatistics.timeDiff(start, moment());
  }

  static boolenIntValue(value: boolean) {
    return value ? 1 : 0;
  }

}

export default GStatistics;
